package com.applink.sell_proof;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Observable;
import java.util.Observer;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.MethodParams;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.dialog.EAlertDialog;
import com.applink.sell_proof.model.Project;

/**
 * 
 * abstract for create/edit/view detail of an Opportunity
 * 
 * @author Van Vu
 * 
 */
public class BaseProject extends BaseActionBarActivity implements Observer,
		OnDateSetListener {

	protected View mLayout;
	protected long mDate = 0;

	Context mContext = this;
	public static BaseProject instantBaseProject = null;

	@Override
	protected void onCreate(Bundle saveInstanceState) {

		super.onCreate(saveInstanceState);
		instantBaseProject = this;
		setContentView(R.layout.opportunity_detail);

		ViewGroup wrapper = (ViewGroup) findViewById(android.R.id.content);

		mLayout = LayoutInflater.from(this)
				.inflate(R.layout.proof_brieft, null);

		// inflate the date input for header
		mLayout.findViewById(R.id.expected_closing_date).setOnClickListener(
				this);

		wrapper.addView(mLayout);

	}

	@Override
	protected void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.sell_proof_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menu_save_opportunity: {

			// create new Opportunity object
			Project project = new Project();

			// set name
			String name = getOpportunityName();

			// set company
			String company = getCompanyName();

			project.setName(name);
			project.setAmount(getEstAmount());
			project.setCustomerCompanyName(company);

			// set date
			project.setDate(mDate);

			// call to server to store
			saveOpportunity(project);
			break;
		}
		case R.id.menu_submit_opportunity: {

			// create new Opportunity object
			Project project = new Project();

			// set name
			String name = ((TextView) mLayout
					.findViewById(R.id.opportunity_name)).getText().toString();

			// set company
			String company = ((TextView) mLayout
					.findViewById(R.id.end_customer_company)).getText()
					.toString();

			// set amount
			String amount = ((TextView) mLayout
					.findViewById(R.id.total_estimated_amount)).getText()
					.toString();

			project.setName(name);
			project.setAmount(Integer.parseInt(amount));
			project.setCustomerCompanyName(company);

			// set date
			project.setDate(mDate);
			System.out.println(">>>> project = " + project.getId());
			// call to server to store
			createOpportunity(project);
			break;
		}
		default:
			break;
		}
		return false;
	}

	protected void createOpportunity(Project project) {
		showloading();
		DataHelper.getInstance().createProject(project);
	}

	protected void saveOpportunity(Project project) {
		showloading();
		DataHelper.getInstance().saveProject(project);

	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		GregorianCalendar closeDate = new GregorianCalendar(year, monthOfYear,
				dayOfMonth);

		mDate = closeDate.getTimeInMillis();

		String textDate = DateFormat.getDateFormat(this).format(mDate);
		
		((TextView) findViewById(R.id.expected_closing_date)).setText(textDate);

	}

	@Override
	public void onClick(View v) {

		// don't forget to call super
		super.onClick(v);

		switch (v.getId()) {
		case R.id.expected_closing_date:

			Calendar date = Calendar.getInstance();

			if (mDate != 0)
				date.setTimeInMillis(mDate);

			DatePickerDialog dateDialog = new DatePickerDialog(this, this,
					date.get(Calendar.YEAR), date.get(Calendar.MONTH),
					date.get(Calendar.DAY_OF_MONTH));

			dateDialog.setTitle(R.string.close_date);

			dateDialog.show();
			break;
		default:
			break;
		}
	}

	@Override
	public void update(Observable arg0, Object data) {

		final DataResult result = (DataResult) data;
		Methods method = result.getMethodName();

		String title = "";

		switch (method) {
		case createOpportunity:
			title = "Create Opportunity";
			break;
		case saveOpportunity:
			title = "Save Opportunity As Draft";
			break;
		case updateOpportunity:
			title = "Update Opportunity";
			break;
		default:
			return;
		}

		String closeBtnText = "close";
		String resultText = "Unsuccessful";
		OnClickListener listener = null;

		if (result.getData() != null) {
			// has a valid response

			resultText = "Successful";

			// set event so click on close dialog the forward the user to the
			// Opportunity Detail view
			listener = new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					switch (which) {
					case Dialog.BUTTON_NEGATIVE:

						Intent intent = new Intent(mContext,
								AllProjectActivity.class);

						mContext.startActivity(intent);
						dialog.dismiss();
						break;
					default:
						break;
					}
				}
			};
		}else{
			MethodParams mp = result.getMethodParam();			
			resultText += " " + mp.getInputData();
		}

		DialogFragment dialogFragment = new EAlertDialog(listener, title,
				closeBtnText, null, resultText);
		dialogFragment.show(this.getSupportFragmentManager(), null);

		hideloading();
	}

	/**
	 * 
	 * @return
	 */
	public String getOpportunityName() {
		String name = ((TextView) mLayout.findViewById(R.id.opportunity_name))
				.getText().toString();
		name = (name.length() > 0) ? name : "Draft";
		return name;
	}

	/**
	 * 
	 * @return
	 */
	public String getCompanyName() {
		String name = ((TextView) mLayout
				.findViewById(R.id.end_customer_company)).getText().toString();
		return name;
	}

	/**
	 * 
	 * @return
	 */
	public int getEstAmount() {

		String amount = ((TextView) mLayout
				.findViewById(R.id.total_estimated_amount)).getText()
				.toString();

		try {
			return Integer.parseInt(amount);
		} catch (Exception e) {
			return 0;
		}
	}
}
